<?php
class agents extends MY_Controller{

	function __construct(){
		parent::__construct();

		if(!$this->checkUserStatus()){
			redirect('login');
		}else{
			$this->aauth->update_activity();
			if(!$this->control(2)){
				redirect('noAccess');
			}

		}

	}


	function index()
	{
		if($_POST){
			
			$pk = $_POST['id'];
			$type = $_POST['type'];
			if($type == 1 ){
				if($this->checkAgent($pk)){
					redirect('agents');
				}else{
					$newAgent = agent::create(array('aauth_user_id'=>$pk));
					if($newAgent){
						redirect('agents');
					}else{
						redirect('error_404');
					}
				}
			}else{
				if(!$this->checkAgent($pk)){
					redirect('agents');
				}else{
					
					$properties_id = property::find('all',array('select'=>'id','conditions'=>array('aauth_user_id'=>$pk)));	
					
					if($properties_id ){
						foreach ($properties_id as $p){
							$update = property::find_by_id($p->id);
							$update->aauth_user_id = '';
							$update->save();
						}
					}
						
						$deleteItem = agent::find($pk);
						$deleteItem->delete();
						redirect('agents');
					
				}
			}
		}
		$agent_id = array();
		$agent = agent::find_by_sql('SELECT * FROM `agents` INNER JOIN `aauth_users` ON(`agents`.aauth_user_id = `aauth_users`.id)');
		if($agent){
		foreach ($agent as $a){
			$agent_id[] = $a->aauth_user_id;
		}
		$users = aauth_user::find('all',array('conditions'=>array('id not in (?)',$agent_id)));
		}else{
			$users = aauth_user::find('all');
		}
		$data['toDoList'] = $this->get_tasks();
		$data['title'] = $this->title('Utilisateurs');
		$data['user'] = $this->aauth->get_user();
		$data['agents'] = $agent;
		$data['users'] = $users;
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/users/agents');
		$this->load->view($this->theme.'/footer');

	}

	private function checkAgent($id)
	{
		
			$item = agent::find_by_aauth_user_id($id);
			if($item){
			return true;
			}else{
			return false;
			}
	}

}